package com.neshai.webapp.service;

import com.neshai.webapp.entity.Invoices;
import com.neshai.webapp.mapper.InvoicesMapper;
import com.stripe.model.Event;
import com.stripe.model.Invoice;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
@RequiredArgsConstructor
public class InvoicePaymentSuccessService {

    private final InvoicesMapper invoicesMapper;
    private final UpgradeService upgradeService;


    public void handleInvoicePaymentSuccess(Event event) {

        Invoice invoicePaymentSuccess = (Invoice) event.getDataObjectDeserializer().getObject().orElse(null);
        if (invoicePaymentSuccess != null) {
            Invoices invoices = new Invoices();

//
//            //status 1 成功， 0 数据库中没有该邮箱，开通失败。
//            if (!users.isEmpty()) {
//                invoices.setStatus(1);
//                User first = users.getFirst();
//                LocalDateTime now = LocalDateTime.now();
//                UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
//                updateWrapper.eq("user_id", first.getUserId()); // 设置更新条件
//                updateWrapper.set("expiry_time", now.plusDays(31)); // 设置要更新的字段
//                updateWrapper.set("recharge_time", now); // 设置要更新的字段
//                updateWrapper.set("vip_level", 1);
//                userMapper.update(null, updateWrapper);
//            } else {
//                invoices.setStatus(0);
//                //TODO 处理开通失败逻辑
//            }

            //status 1 成功， 0 数据库中没有该邮箱，开通失败。
            if (upgradeService.paidAndUpgradeByEmail(invoicePaymentSuccess.getCustomerEmail(), invoicePaymentSuccess.getAmountPaid())) {
                invoices.setStatus(1);
            } else {
                invoices.setStatus(0);
//              //TODO 处理开通失败逻辑
            }

            invoices.setInvoice(invoicePaymentSuccess.getId());
            invoices.setCustomerEmail(invoicePaymentSuccess.getCustomerEmail());
            invoices.setProduct(invoicePaymentSuccess.getLines().getData().getFirst().getPrice().getProduct());
            invoices.setPeriodEnd(invoicePaymentSuccess.getPeriodEnd());
            invoices.setCurrency(invoicePaymentSuccess.getCurrency());
            invoices.setAmountDue(invoicePaymentSuccess.getAmountDue());
            invoices.setAmountPaid(invoicePaymentSuccess.getAmountPaid());
            invoices.setHostedInvoiceUrl(invoicePaymentSuccess.getHostedInvoiceUrl());
            invoices.setCustomer(invoicePaymentSuccess.getCustomer());
            invoices.setCustomerName(invoicePaymentSuccess.getCustomerName());
            invoices.setCustomerPhone(invoicePaymentSuccess.getCustomerPhone());
            invoices.setCompletedAt(LocalDateTime.now());
            invoicesMapper.insert(invoices);
        }
    }
}
